<template>
  <div>
    <div
      class="tooltip"
      @mouseenter="handleEnter"
      @mouseleave="showTooltip = false"
    >
   
      <slot></slot>
      <div v-if="showTooltip"  :class="[`tooltip-content ${position}`]" :style="contentStyle">
        {{ context }}
    </div>
    <!-- 计算宽度 的隐藏元素-->
    <div class="computedWidthHideDom" ref="hideDmoRef">{{ context }}</div>
    </div>
  </div>
</template>

<script setup name="Tooltip">
import { ref , defineProps, nextTick } from 'vue';

const {context , position} = defineProps({
    context: {
        type: String,
        default:''
  },
  position: {
    type: String,
    default:'top'
  }
})

const showTooltip = ref(false);
const contentStyle = ref({});
const hideDmoRef = ref();

const handleEnter = () => {
    showTooltip.value = true;
    const width = hideDmoRef.value.getBoundingClientRect().width;
    nextTick().then(() => {
        contentStyle.value = {
            width: `${width}px`,
            left:`calc(50% - ${Math.ceil(width / 2) + 2}px)`,
        }
    })
}


</script>

<style scoped>
.tooltip {
  position: relative;
  display: flex;
}

.tooltip-content {
  visibility: hidden;
  background-color: rgba(0, 0, 0, 0.7);
  color: #fff;
  text-align: center;
  border-radius: 6px;
  padding: 0 5px;
  height: 28px;
  line-height: 28px;
  position: absolute;
  z-index: 1;
  font-size: 12px;
}
.bottom{
  bottom: calc(100% + 6px);
}
.top{
  top:22px;
}
.top::after{
  top:-10px;
  transform: rotate(180deg);
}

.tooltip-content::after {
  content: '';
  position: absolute;
  /* top:100%; */
  left: calc(50% - 5px);
  border-width: 5px;
  border-style: solid;
  border-color: rgba(0, 0, 0, 0.7) transparent transparent transparent;
}

.tooltip:hover .tooltip-content {
  visibility: visible;
}
.computedWidthHideDom{
    font-size: 12px;
    padding: 0 5px;
    opacity: 0;
    position: fixed;
    top: 10000px;
}
</style>
